package com.xxx.common.controller;


import com.github.pagehelper.PageInfo;
import com.xxx.common.entity.User;
import com.xxx.common.service.UserService;
import com.xxx.common.utils.Result;
import com.xxx.common.utils.ResultUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/common/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getUserInfo")
    public Result getUserInfo(User user,@RequestParam(value="pageNum",defaultValue = "1") Integer pageNum,
                              @RequestParam(value="pageSize",defaultValue = "10") Integer pageSize){
        try{
            PageInfo<User> data = userService.selectUserInfo(user,pageNum,pageSize);
            return ResultUtil.success(1,"成功",data);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"失败");
        }
    }

    @PostMapping("/saveAndUpdateUserInfo")
    public Result saveAndUpdateUserInfo(User user){
        try {
            Integer count = userService.saveAndUpdateUserInfo(user);
            return ResultUtil.success(1,"成功",count);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"失败");
        }
    }

    @DeleteMapping("/delUserInfo")
    public Result delUserInfo(Integer id){
        try {
            Integer count = userService.delUserInfo(id);
            return ResultUtil.success(1,"成功",count);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"失败");
        }
    }



    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Result login(String userName, String password){
        try {
            User user = userService.login(userName,password);
            if (user == null){
                return ResultUtil.error(-1,"登录失败,用户名或者密码错误");
            }else {
                return ResultUtil.success(1,"登录成功",user);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"发生异常!");
        }
    }

}

